import * as React from "react"
import { VersionSwitcher } from "@/components/version-switcher"
import { SearchForm } from "@/components/Search-form"
import {
  Sidebar,
  SidebarContent,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarMenuSub,
  SidebarRail,
} from "@/components/ui/sidebar"
import { usePathname } from "next/navigation"
import { getSidebarData } from "@/components/database/index";
import Link from "next/link"
import { SidebarGroupType, SidebarItem } from "@/types"
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
import { ChevronRight } from "lucide-react"

// 判断当前路径是否在菜单树下
function isPathInMenu(items: SidebarItem[] = [], pathname: string): boolean {
  return items.some(item => {
    if (item.url === pathname) return true;
    if (item.items && Array.isArray(item.items) && item.items.length > 0) {
      return isPathInMenu(item.items, pathname);
    }
    return false;
  });
}

// 递归渲染多级菜单
function SidebarMenuRecursive({ items, pathname }: { items: SidebarItem[]; pathname: string }) {
  return (
    <>
     {items.map((item) =>
        Array.isArray(item.items) && item.items.length > 0 ? (
          <Collapsible
            key={item.title}
            asChild
            defaultOpen={isPathInMenu(item.items, pathname) || pathname === item.url}
            className="group/collapsible"
          >
            <SidebarMenuItem>
              <CollapsibleTrigger asChild>
                <SidebarMenuButton tooltip={item.title}>
                  {item.icon && <item.icon />}
                  <span>{item.title}</span>
                  <ChevronRight className="ml-auto transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90" />
                </SidebarMenuButton>
              </CollapsibleTrigger>
              <CollapsibleContent>
                <SidebarMenuSub>
                  <SidebarMenuRecursive items={Array.isArray(item.items) ? item.items : []} pathname={pathname} />
                </SidebarMenuSub>
              </CollapsibleContent>
            </SidebarMenuItem>
          </Collapsible>
        ) : (
          <SidebarMenuItem key={item.title}>
            <SidebarMenuButton
              asChild
              isActive={
                item.url !== "#" &&
                (
                  item.url === "/"
                    ? pathname === "/"
                    : pathname.startsWith(item.url)
                )
              }
            >
              {item.url.startsWith("/") &&
              !item.url.startsWith("//") &&
              !/^https?:\/\//.test(item.url) ? (
                <Link href={item.url}>
                  {item.icon && <item.icon />}
                  <span>{item.title}</span>
                </Link>
              ) : (
                <span>
                  {item.icon && <item.icon />}
                  <span>{item.title}</span>
                </span>
              )}
            </SidebarMenuButton>
          </SidebarMenuItem>
        )
      )}
    </>
  );
}

export function AppSidebar(props: React.ComponentProps<typeof Sidebar>) {
  const pathname = usePathname();
  const [data, setData] = React.useState<{ versions: string[]; navMain: SidebarGroupType[] } | null>(null);

  React.useEffect(() => {
    let mounted = true;
    getSidebarData().then((result) => {
      if (mounted && result && result.versions && result.navMain) {
        setData({ versions: result.versions, navMain: result.navMain });
      }
    });
    return () => {
      mounted = false;
    };
  }, []);

  if (!data || !data.versions || !data.versions.length || !data.navMain) {
    return null;
  }

  return (
    <Sidebar {...props} collapsible="icon">
      <SidebarHeader>
        <VersionSwitcher
          versions={data.versions}
          defaultVersion={data.versions[0] || ""}
        />
        <SearchForm />
      </SidebarHeader>
      <SidebarContent>
        {data.navMain.map((item: SidebarGroupType) => (
          <SidebarGroup key={item.title}>
            <SidebarGroupLabel className="font-semibold text-sm text-gray-500 uppercase">{item.title}</SidebarGroupLabel>
            <SidebarGroupContent>
              <SidebarMenu>
                <SidebarMenuRecursive items={item.items} pathname={pathname} />
              </SidebarMenu>
            </SidebarGroupContent>
          </SidebarGroup>
        ))}
      </SidebarContent>
      <SidebarRail />
    </Sidebar>
  )
}